import { defineStore } from 'pinia';
import {
  addAddress,
  updateAddress,
  deleteAddress,
  getAddressList,
  getAddressDetail,
  setDefaultAddress,
  getDefaultAddress
} from '../api/address.js';

export const useAddressStore = defineStore('address', {
  state: () => ({
    // 地址列表
    addressList: [],
    // 默认地址
    defaultAddress: null,
    // 当前选中的地址详情
    currentAddress: null
  }),

  getters: {
    // 获取地址列表
    getAddressList: (state) => state.addressList,
    // 获取默认地址
    getDefaultAddress: (state) => state.defaultAddress || state.addressList.find(addr => addr.isDefault === 1),
    // 获取当前选中的地址
    getCurrentAddress: (state) => state.currentAddress,
    // 获取地址总数
    getAddressCount: (state) => state.addressList.length
  },

  actions: {
    // 加载地址列表
    async loadAddressList() {
      try {
        const res = await getAddressList();
        if (res.code === 200) {
          // 过滤掉已删除的地址
          this.addressList = res.data.filter(addr => !addr.deleted);
          // 自动设置默认地址
          const defaultAddr = this.addressList.find(addr => addr.isDefault === 1);
          if (defaultAddr) {
            this.defaultAddress = defaultAddr;
          }
        }
        return res;
      } catch (error) {
        console.error('加载地址列表失败:', error);
        throw error;
      }
    },

    // 加载默认地址
    async loadDefaultAddress() {
      try {
        const res = await getDefaultAddress();
        if (res.code === 200) {
          this.defaultAddress = res.data;
        }
        return res;
      } catch (error) {
        console.error('加载默认地址失败:', error);
        throw error;
      }
    },

    // 加载地址详情
    async loadAddressDetail(addressId) {
      try {
        const res = await getAddressDetail(addressId);
        if (res.code === 200) {
          this.currentAddress = res.data;
        }
        return res;
      } catch (error) {
        console.error('加载地址详情失败:', error);
        throw error;
      }
    },

    // 添加地址
    async addNewAddress(addressDTO) {
      try {
        const res = await addAddress({
          ...addressDTO,
          userId: uni.getStorageSync('userId'), // 添加用户ID
          deleted: 0 // 新增地址默认未删除
        });
        if (res.code === 200) {
          // 如果添加的是默认地址，更新默认地址
          if (addressDTO.isDefault === 1) {
            this.defaultAddress = { ...addressDTO, id: res.data };
          }
          // 重新加载地址列表
          await this.loadAddressList();
        }
        return res;
      } catch (error) {
        console.error('添加地址失败:', error);
        throw error;
      }
    },

    // 更新地址
    async updateExistingAddress(addressDTO) {
      try {
        const res = await updateAddress({
          ...addressDTO,
          updateTime: new Date().toISOString() // 更新时间
        });
        if (res.code === 200) {
          // 如果更新的是默认地址，更新默认地址
          if (addressDTO.isDefault === 1) {
            this.defaultAddress = addressDTO;
          }
          // 如果更新的是当前选中的地址，更新当前地址
          if (this.currentAddress?.id === addressDTO.id) {
            this.currentAddress = addressDTO;
          }
          // 更新地址列表中的对应地址
          const index = this.addressList.findIndex(addr => addr.id === addressDTO.id);
          if (index !== -1) {
            this.addressList[index] = addressDTO;
          }
        }
        return res;
      } catch (error) {
        console.error('更新地址失败:', error);
        throw error;
      }
    },

    // 删除地址
    async deleteExistingAddress(addressId) {
      try {
        const res = await deleteAddress(addressId);
        if (res.code === 200) {
          // 如果删除的是默认地址，清空默认地址
          if (this.defaultAddress?.id === addressId) {
            this.defaultAddress = null;
          }
          // 如果删除的是当前选中的地址，清空当前地址
          if (this.currentAddress?.id === addressId) {
            this.currentAddress = null;
          }
          // 从列表中移除该地址
          this.addressList = this.addressList.filter(addr => addr.id !== addressId);
        }
        return res;
      } catch (error) {
        console.error('删除地址失败:', error);
        throw error;
      }
    },

    // 设置默认地址
    async setAddressAsDefault(addressId) {
      try {
        const res = await setDefaultAddress(addressId);
        if (res.code === 200) {
          // 更新默认地址
          const address = this.addressList.find(addr => addr.id === addressId);
          if (address) {
            this.defaultAddress = { ...address, isDefault: 1 };
            // 更新地址列表中的默认状态
            this.addressList = this.addressList.map(addr => ({
              ...addr,
              isDefault: addr.id === addressId ? 1 : 0
            }));
          }
        }
        return res;
      } catch (error) {
        console.error('设置默认地址失败:', error);
        throw error;
      }
    },

    // 设置当前选中的地址
    setCurrentAddress(address) {
      this.currentAddress = address;
    }
  }
});
